#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>




/*
 * ./led_test 0|1|2... on
 * ./led_test 0|1|2.. off
 * ./led_test 0|1|2..
 */
int main(int argc, char **argv)
{
	static int fd;
	char buf[2];//buf[0] store led number,buf[1] stores on_off state
	/* 1. 判断参数 */
	if (argc != 2 && argc != 3) 
	{
		printf("Usage: %s < 0|1|2|...>  [on/off]\n", argv[0]);
		return -1;
	}

	/* 2. 打开文件 */
	fd = open("/dev/led", O_RDWR);
	if (fd == -1)
	{
		printf("can not open led %d \n", argv[1]);
		return -1;
	}

   // buf[0] = strtol(argv[1], NULL, 10);
	buf[0] = atoi(argv[1]);

    if(argc == 3)
	{
		
        if(strcmp(argv[2], "on") == 0)
		{
			buf[1] = 0;
		}
		else
		{
			buf[1] = 1;
		}
		write(fd, buf, 2);
	}
	else
	{
		int ret;
		ret = read(fd,buf,2);
		if(ret == 2)
		printf("led %d is %s\n",buf[0],buf[1] == 1 ? "off" : "on");
	}
	close(fd);
	
	return 0;
}


